<template>
  <view>
    <kk-container
      :refresherEnabled="true"
      title="消息通知"
      :isShowHeader="true"
      @handlerRefresh="handlerRefresh"
      @handlerReachBottom="handlerReachBottom"
      :loadMoreStatus="loadMoreStatus"
    >
      <kk-no-data v-if="requestComplete && list && list.length === 0" />
      <view
        v-if="requestComplete && list && list.length > 0"
        style="margin-top: 24rpx"
      >
        <view v-for="(item, index) in list" :key="index">
          <NotifyItem :data="item" />
        </view>
      </view>
    </kk-container>
  </view>
</template>

<script setup lang="ts">
import { onLoad, onShow } from "@dcloudio/uni-app";
import { ref } from "vue";
import { getMessageNotificationList } from "@/api/message/index";

import NotifyItem from "./components/notifyItem.vue";
import { onUnmounted } from "vue";

const list = ref([]);
const currentPage = ref(1);
const total = ref(0);
const loadMoreStatus = ref("");
const requestComplete = ref(false);
const timer = ref();

onLoad((options) => {
  getList(currentPage.value);
});

const getList = async (page: Number) => {
  const params = {
    page,
    pageSize: 10,
  };
  const data = (await getMessageNotificationList(params).catch(
    () => {}
  )) as any;
  requestComplete.value = true;
  if (data && data.data) {
    currentPage.value = page;
    if (page === 1) {
      list.value = data.data.list || [];
    } else {
      list.value = list.value.concat(data.data.list || []);
    }
    total.value = data.data.count || 0;
    if (list.value.length >= total.value && total.value > 0) {
      loadMoreStatus.value = "no-more";
    } else {
      loadMoreStatus.value = "";
    }
  }
};

// 加载更多数据
const handlerReachBottom = () => {
  if (list.value.length < total.value) {
    // 可以继续加载更多
    loadMoreStatus.value = "loading";
    getList(currentPage.value + 1);
  }
};

// 刷新页面
const handlerRefresh = () => {
  timer.value = setTimeout(() => {
    currentPage.value = 1;
    getList(currentPage.value);
  }, 100);
};

onUnmounted(() => {
  if (timer.value) {
    clearTimeout(timer.value);
  }
});
</script>

<style lang="scss" scoped></style>
